<template>
  <div class="wrapper">
    <div class="search">
      <div class="search__back iconfont" @click="handleBackClick">&#xe697;</div>
      <div class="search__content">
        <span class="search__content__icon iconfont">&#xe6c5;</span>
        <input
          class="search__content__input"
          placeholder="请输入商品名称"
          v-model="keyword"
          @change="handleSearchInputChange"
        />
      </div>
    </div>
    <router-link
      v-for="item in searchList"
      :key="item._id"
      :to="`/shop/${item.id}`"
    >
      <ShopInfo :item="item" />
    </router-link>
  </div>
</template>

<script>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import ShopInfo from "../../components/ShopInfo";

//点击回退逻辑
const useBackRouterEffect = () => {
  const router = useRouter();
  const handleBackClick = () => {
    router.back();
  };
  return handleBackClick;
};

//热词相关逻辑
const useSearchListEffect = () => {
  const searchList = ref([]);
  const getSearchList = async (keyword) => {
    axios
      .get("/api/shop/search", { keyword })
      .then((result) => {
        let { data } = result.data;
        if (result.status == 200) {
          searchList.value = data; //热门搜索数据
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  return { searchList, getSearchList };
};

export default {
  name: "SearchList",
  components: {
    ShopInfo,
  },
  setup() {
    const route = useRoute();
    //搜索关键词逻辑
    const keyword = ref(route.query.keyword || ""); //接收跳转参数
    const handleSearchInputChange = () => {
      getSearchList(keyword.value);
    };
    const handleBackClick = useBackRouterEffect();
    //获取搜索列表
    const { searchList, getSearchList } = useSearchListEffect();
    getSearchList(keyword.value);
    return {
      keyword,
      searchList,
      getSearchList,
      handleBackClick,
      handleSearchInputChange,
    };
  },
};
</script>

<style lang="scss" scoped>
@import "../../style/viriables.scss";
.wrapper {
  padding: 0 0.18rem;
  //去掉下划线
  a {
    text-decoration: none;
  }
}
.search {
  display: flex;
  margin: 0.14rem 0 0.04rem 0;
  line-height: 0.32rem;
  &__back {
    width: 0.3rem;
    font-size: 0.24rem;
    color: $search-fontColor;
  }
  &__content {
    display: flex;
    flex: 1;
    background: #f5f5f5;
    border-radius: 0.16rem;
    &__icon {
      width: 0.44rem;
      text-align: center;
      color: $search-fontColor;
    }
    &__input {
      display: block;
      width: 100%;
      padding-right: 0.2rem;
      border: none;
      outline: none;
      background: none;
      height: 0.32rem;
      font-size: 0.14rem;
      color: $content-fontcolor;
      &::placeholder {
        color: $content-fontcolor;
      }
    }
  }
}
</style>
